angular.module("application")
.controller('hsplaceCtrl', function($scope, $timeout, refDataProcess, placeMapProcess, renderProcess) {
	
	$scope.places = {}
	$scope.searchPlace = '';

	refDataProcess.getPlaceData().then(function(data) {
		$timeout(function() {
			$scope.$apply(function() {
				$scope.$parent.loadingView = false;
			});
		},200)
		.then(function() {
			$("#main-content").css({ // Set map Container Size
				'width': viewport().width - 100 + 'px',
				'height': viewport().height - 80 + 'px'
			});
			placeMapProcess.initialMap('wo');
			placeMapProcess.setMap(data);

			renderProcess.setListHeight();
		});

		$scope.places = data;		
	});

	$scope.viewPlace = function(id) {
		placeMapProcess.changeView(id);
	}
})

// ====================================================================================================
// ====================================================================================================

.controller('hspersonCtrl', function($scope, refDataProcess) {
	$scope.persons = {};
	$scope.categories = [];
	$scope.fName = "";

	refDataProcess.getCategory().then(function(data) {
		parentArr = [];
		childArr = [];
		angular.forEach(data, function(cat) {
			if(!cat.parent) parentArr.push(cat);
			else {
				cat.name = ' -- ' + cat.name;
				childArr.push(cat);
			}
		});		
		angular.forEach(parentArr, function(par) {
			$scope.categories.push(par);
			angular.forEach(childArr, function(child) {
				if(child.parent == par._id) {
					$scope.categories.push(child);
				}
			});
		});
	})

	refDataProcess.getPersonData().then(function(data) {
		setTimeout(function() {
			$scope.$apply(function() {
				$scope.$parent.loadingView = false;
			});
		},200);
		$scope.persons = data;
	});

})

// ====================================================================================================
// ====================================================================================================

.controller('referenceCtrl', function($scope, $routeParams, $sce, $timeout, refDataProcess, mapProcess) {
	$scope.categories = [];
	$scope.fName = "";
	$scope.mapIds = [];

	refId = $routeParams.refId;
	refDataProcess.getReference(refId).then(function(data) {
		$scope.data = data;
		$scope.type = data.type;
		$scope.title = data.title;
		$scope.content = $sce.trustAsHtml(data.content);

		$timeout(function() {
			$scope.$apply(function() {
				$scope.$parent.loadingView = false;
			});
			$('.lesson-maps').each(function() {
				$scope.mapIds.push($(this).attr('id'));
			});
		},200)
		.then(function() {
			// console.log($scope.maps);
			var maps = $scope.mapIds;
			for(m in maps) {
				mapProcess.initialMap(maps[m]);
			};
		})
	});

})

// ====================================================================================================
// ====================================================================================================
// ====================================================================================================
// ====================================================================================================

.factory('refDataProcess', function($http, BASE_URL) {
	return {
		getPlaceData: function() {
			return $http.post(BASE_URL + 'application_api/reference/getPlaces')
			.then(function(promise) {
				return promise.data;
			})
		},
		getPersonData: function() {
			return $http.post(BASE_URL + 'application_api/reference/getPersons')
			.then(function(promise) {
				return promise.data;
			})
		},
		getCategory: function() {
			return $http.post(BASE_URL + 'application_api/category/getAllCats')
			.then(function(promise) {
				return promise.data;
			})
		},
		getReference: function(refId) {
			return $http.post(BASE_URL + 'application_api/reference/getReference/' + refId)
			.then(function(promise) {
				console.log(promise.data);
				return promise.data;
			})
		}
	}
})

.factory('placeMapProcess', function($http, BASE_URL) {
	var myStyle = [{"featureType":"road","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"labels.text","stylers":[{"visibility":"off"}]},{"featureType":"administrative","elementType":"geometry","stylers":[{"visibility":"on"},{"weight":0.8},{"color":"#DAD5CC"}]},{"featureType":"administrative.country","elementType":"geometry.stroke","stylers":[{"weight":0.8},{"color":"#b16736"}]},{"featureType":"administrative","elementType":"labels","stylers":[{"weight":0.1},{"color":"#e1e1e1"}]},{"featureType":"landscape.natural","elementType":"geometry.fill","stylers":[{"visibility":"on"},{"color":"#f0ece6"}]},{"featureType":"poi","stylers":[{"visibility":"off"}]},{"featureType":"transit","stylers":[{"visibility":"off"}]}];
	var bigMap = null;
	var mapConfig = [
		{center: {lat: 15.961329, lng: 106.259766}, zoom: 5},
		{center: {lat: 38.5997, lng: 51.5039 }, zoom: 2}
	]
	var image = {
	    url: BASE_URL + 'assets/images/flag-marker (3).png',
	    size: new google.maps.Size(48, 48), // This marker is 48 pixels wide by 48 pixels tall.
	    origin: new google.maps.Point(0,0), // The origin for this image is 0,0.
	    anchor: new google.maps.Point(24, 48) // The anchor for this image is the base of the flagpole at 24,48.
	}
	var image2 = {
	    url: BASE_URL + 'assets/images/flag-marker (2).png',
	    size: new google.maps.Size(48, 48), // This marker is 48 pixels wide by 48 pixels tall.
	    origin: new google.maps.Point(0,0), // The origin for this image is 0,0.
	    anchor: new google.maps.Point(24, 48) // The anchor for this image is the base of the flagpole at 24,48.
	}

	var elementsArr = [];
	var infowLast;

	return {
		initialMap: function(region) {
			var v = null; 
			if(region == 'vn') {v = mapConfig[0];}
			else {v = mapConfig[1];}

			// Initialize Static Map
			var mapOptions = {
				mapTypeControlOptions: {
					mapTypeIds: ['mystyle', google.maps.MapTypeId.TERRAIN]
				},
				// scrollwheel: false,
				mapTypeId: 'mystyle',
				// disableDoubleClickZoom: true,
				mapTypeControl: false,
				zoomControl: true,
				streetViewControl: false,
				center: v.center,
				zoom: v.zoom
			};
			bigMap = new google.maps.Map(document.getElementById("bigmap"),mapOptions);
			bigMap.mapTypes.set('mystyle',new google.maps.StyledMapType(myStyle,{ name:'My Style'}));
			google.maps.event.addListener(bigMap, 'click', function(event) {
				if(infowLast) infowLast.close();
			});
			google.maps.event.addDomListener(window, "resize", function() {
				google.maps.event.trigger(bigMap, "resize");
			});
			return bigMap;
		},
		setMap: function(data) {
			angular.forEach(data, function(place) {
				point = place.position.split(',');
				latlng = new google.maps.LatLng(point[0], point[1]);
				if(place.region == 'wo') {
					var marker = new google.maps.Marker({
						position: latlng,
						icon: image2,
						map: bigMap,
						title: place.title
					});
				}
				else {
					var marker = new google.maps.Marker({
						position: latlng,
						icon: image,
						map: bigMap,
						title: place.title
					});
				}
					
				elementsArr.push({
					id: place._id.$id,
					point: marker
				});

				strContent = '<div class="map-content">' +
				'<h3 class="event">' + place.title + '</h3>' +
				'<p class="link"><a href="#/reference/' + place._id.$id + '">Xem bài viết</a></p>' +
				'<p class="place-thumb"><img src="' + place.image + '" /></p>' +
				'</div>';
				var infowindowM = new google.maps.InfoWindow({ content: strContent });

				google.maps.event.addListener(marker,'click', (function(marker,strContent,infowindowM){ 
					return function() {
						if(infowLast) infowLast.close();
						infowindowM.setContent(strContent);
						infowindowM.open(bigMap,marker);
						infowLast = infowindowM;
					};
				})(marker,strContent,infowindowM));
			})
		},
		changeView: function(placeId) {
			if(placeId == 'all') {
				angular.forEach(elementsArr, function(place) {
					place.point.setVisible(true);
				});
				return;
			}
			angular.forEach(elementsArr, function(place) {
				if(place.id != placeId) {
					place.point.setVisible(false);
				}
				if(place.id == placeId) {
					place.point.setVisible(true);
					bigMap.panTo(place.point.getPosition());
				}
			});
		}
	}
})